import { useUserStoreWithOut } from '@/store/modules/user'
import * as mainRouter from '@/router/routes/modules/router'
import { isArray } from '@/utils/is'

export function setRootPathByPermission(): string {
    const routerMap = isArray(mainRouter.default) ? mainRouter.default : [mainRouter.default]
    // 默认进入无权限页面
    let result = import.meta.env.VITE_PUBLIC_PATH + '/403'
    const userStore = useUserStoreWithOut()
    const permissionCodeMap = userStore.getPermissionMap
    const path = iterationMenu(routerMap, permissionCodeMap);
    if (path) {
        result = path
    }
    return result
}

function iterationMenu(menu: any, permissionCodeMap: any): string {
    for (const item of menu) {
        if (item.children && item.children.length) {
            const _deepPath = iterationMenu(item.children, permissionCodeMap)
            // 直接返回会引起二级菜单没匹配到的时，不继续匹配的问题
            if (_deepPath) {
                return _deepPath
            }
        }
        if (permissionCodeMap?.includes(item.meta.code)) {
            return item.path
        }
    }
    return ''
}

